package club.dmyang.controller;

import club.dmyang.common.vo.ResposeVo;
import club.dmyang.entity.Category;
import club.dmyang.service.CategoryService;
import org.omg.PortableInterceptor.INACTIVE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Created by brss on 2018/7/15.
 */
@Controller
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 分页列出所有分类
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public ResposeVo list(Integer page, Integer limit){
        List<Category> categoryList = categoryService.findByPageAndLimit(page, limit);
        //查询数据库所有分类记录
        int count = categoryService.findtAllNums();
        return new ResposeVo(0,"成功",count,categoryList);
    }

    /**
     * 删除某个分类
     * @param cid
     * @return
     */
    @RequestMapping("/delete/{cid}")
    @ResponseBody
    public String delete(@PathVariable("cid") Integer cid){
        if (categoryService.deleteOneCategory(cid)) {
            return "删除分类成功！";
        }else {
            return "删除分类失败，请确保分类下面没有文章";
        }
    }

    /**
     * 跳转到编辑页面
     * @param cid
     * @param model
     * @return
     */
    @RequestMapping("/edit/{cid}")
    public String edit(@PathVariable("cid") Integer cid, Model model){
        Category category = categoryService.findOneById(cid);
        model.addAttribute("category",category);
        return "admin/category-add";
    }

    /**
     * 更新一个分类
     * @param category
     * @return
     */
    @ResponseBody
    @RequestMapping("/update")
    public String update(Category category){
        boolean b = categoryService.updateOneCategory(category);
        if (b)
            return "更新分类成功！";
        else
            return "更新分类失败！";
    }

    @ResponseBody
    @RequestMapping("/add")
    public String add(Category category){
        boolean b = categoryService.addOneCategory(category);
        if (b)
            return "添加分类成功";
        else
            return "添加分类失败";
    }
}
